package com.zhu.transaction.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Zhu
 * @createtime 2021/2/25-9:42
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        // 从session当中获取特定的数据
        Object obj = session.getAttribute("user");
        if (obj == null) {
            // 未登录，重定向到登录页面
            session.setAttribute("message","请先登录");
            //信息存放3秒后，自动过期
            session.setMaxInactiveInterval(3);
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        // 已登录，继续向后调用
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
